package com.hujiang.basic.search.common.converter.req;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.hujiang.basic.search.common.component.HJElasticSearchClient;
import com.hujiang.basic.search.model.HJBulkIndexRequest;


@Component
public class BulkIndexRequestConverter extends BulkRequestConverter<HJBulkIndexRequest> {

    @Autowired
    private HJElasticSearchClient client;

    @Override
    public BulkRequestBuilder convert(HJBulkIndexRequest in) {
        BulkRequestBuilder bulk = client.prepareBulk();
        for (int i = 0; i < in.getSources().size(); i++) {
            JSONObject json = in.getSources().getJSONObject(i);
            String id = extractId(json);
            IndexRequestBuilder irb = client.prepareIndex(in.getIndex(), in.getType(), id, json);
            bulk.add(irb);
        }
        return bulk;
    }
}
